<?php

/**
 * This is the model class for table "languages".
 *
 * The followings are the available columns in table 'languages':
 * @property integer $id
 * @property integer $pageId
 * @property string $extension
 * @property string $value
 * @property string $name
 * @property string $email
 * @property string $userId
 * @property string $createdAt
 * @property string $updatedAt
 */
class Language extends ActiveRecord {

	public $file;
	// This field is exclusively used when finding latest translation.
	public $dialect;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Language the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'languages';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('value', 'length', 'max'=>32),
			array(
				'file',
				'EPhotoValidator',
				'allowEmpty'=>false,
				'mimeType'=>array('image/jpeg', 'image/png'),
				'on'=>'insert'
			),
			array(
				'file',
				'EPhotoValidator',
				'allowEmpty'=>true,
				'mimeType'=>array('image/jpeg', 'image/png'),
				'on'=>'update'
			),
			array('name, email', 'length', 'max'=>255),
			array('value', 'required'),
			array('name', 'required', 'on'=>'insertGuest'),
			array('email', 'length', 'max'=>128),
			array('email', 'email'),
			array('createdAt, updatedAt', 'safe'),
			array('value, name, email, userId', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'page'=>array(self::BELONGS_TO, 'Page', 'pageId'),
			'comments'=>array(self::HAS_MANY, 'Comment', 'languageId'),
			'translations'=>array(self::HAS_MANY, 'Translation', 'languageId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id'=>'ID',
			'file'=>'Image',
			'pageId'=>'Page',
			'extension'=>'Extension',
			'value'=>'Language',
			'name'=>'Uploader',
			'email'=>'Uploader Email',
			'userId'=>'User',
			'viewCount'=>'View',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('value', $this->value, true);
		$criteria->compare('name', $this->name, true);
		$criteria->compare('email', $this->email, true);
		$criteria->compare('userId', $this->userId, true);

		return new CActiveDataProvider($this, array('criteria'=>$criteria));
	}

	protected function beforeSave() {
		if (!$this->file) {
			$this->file = CUploadedFile::getInstance($this, 'file');
		}
		if ($this->file) {
			if ($this->extension) {
				if ($this->extension != $this->file->extensionName) {
					unlink($this->filePath);
				}
			}
			$this->extension = $this->file->extensionName;
		}
		return parent::beforeSave();
	}

	protected function afterSave() {
		parent::afterSave();
		if ($this->file) {
			$this->file->saveAs($this->filePath);
			$image = Yii::app()->image->load($this->filePath);
			$image->resize(150, NULL, 4)->quality(75);
			$image->save($this->fileThumbnailPath);
		}
		$this->page->save(false);
	}

	public function getFilePath() {
		$folder = Yii::app()->params['files'] . '/languages';
		return "{$folder}/{$this->id}.{$this->extension}";
	}

	public function getFileThumbnailPath() {
		$folder = Yii::app()->params['files'] . '/languages/_thumbnails';
		return "{$folder}/{$this->id}.jpg";
	}

	public function getFileUrl() {
		$baseUrl = Yii::app()->request->baseUrl;
		return "$baseUrl/files/languages/{$this->id}.{$this->extension}";
	}

	public function getFileThumbnailUrl() {
		$baseUrl = Yii::app()->request->baseUrl;
		return "$baseUrl/files/languages/_thumbnails/{$this->id}.jpg";
	}

	/* Deprecated */

	public function getUploader() {
		return $this->uploaderName;
	}

	public function getUploaderName() {
		if ($this->userId) {
			$params = array(':user_id'=>$this->userId);
			$user = Profile::model()->find('user_id = :user_id', $params);
			if ($user) {
				return $user->firstname ? $user->firstname : 'Anonymous';
			}
		} else {
			return $this->name ? $this->name : 'Anonymous';
		}
	}

	protected function afterDelete() {
		parent::afterDelete();
		unlink($this->filePath);
		unlink($this->fileThumbnailPath);
	}

	public static function createList($chapterId) {
		$where = array(
			':chapterId'=>$chapterId
		);
		$pages = Yii::app()->db->createCommand()
			->select('l.id, p.sequence, p.subSequence, l.value')
			->from('languages l')
			->join('pages p', 'l.pageId = p.id')
			->where('p.chapterId = :chapterId', $where)
			->order('p.sequence, p.subSequence')
			->queryAll();
		$list = array();
		foreach ($pages as $page) {
			$text = $page['sequence'] . $page['subSequence'] . ' - ' .
				$page['value'];
			$list[$page['id']] = $text;
		}
		return $list;
	}

	protected $_dialects = null;

	public function getDialects() {
		if ($this->_dialects === null) {
			$where = array(':languageId'=>$this->id);
			$dialects = Yii::app()->db->createCommand()
				->selectDistinct('dialect')
				->from('translations')
				->where('languageId = :languageId', $where)
				->order('dialect')
				->queryAll();
			$this->_dialects = array();
			foreach ($dialects as $dialect) {
				$this->_dialects[] = $dialect['dialect'];
			}
		}
		return $this->_dialects;
	}

	protected $_alternatives = null;

	public function getAlternatives() {
		if ($this->_alternatives === null) {
			$condition = 'pageId = :pageId AND id <> :id';
			$params = array(
				':pageId'=>$this->pageId,
				':id'=>$this->id
			);
			$alt = Language::model()->findAll($condition, $params);
			$this->_alternatives = $alt;
		}
		return $this->_alternatives;
	}

}